<?php

declare(strict_types = 1);

/**
 * Author: Jesse
 * Email : jessedev@163.com
 * Date: 2024/7/3 01:12
 * FileName: DispatcherFactory.php
 * DESC: The Relentless Pursuit of Perfection.
 */

namespace Common\Kernel\Router;


use Hyperf\Stringable\Str;

/**
 * 路由注册规则重写
 * 好像用切面也可以实现，现在用的是容器
 */
class DispatcherFactory extends \Hyperf\HttpServer\Router\DispatcherFactory
{
    /**
     * 获取路由前缀
     *
     * @param string $className
     * @param string $prefix
     * @return string
     */
    protected function getPrefix(string $className, string $prefix): string
    {
        if (!$prefix) {
            $handledNamespace = Str::replaceFirst('Controller', '', Str::after($className, '\\Controller\\'));
            $handledNamespace = str_replace('\\', '/', $handledNamespace);

            $prefix = Str::snake($handledNamespace);
            $prefix = str_replace('/_', '/', $prefix);

            // 多模块路由
            $namespace = Str::before($className, '\\Controller\\');
            $namespace = Str::after($namespace, '\\');
            $namespacePrefix = Str::snake($namespace);
            $namespacePrefix = str_replace('/_', '/', $namespacePrefix);
            $prefix = $namespacePrefix . '/' . $prefix;
        }
        if ($prefix[0] !== '/') {
            $prefix = '/' . $prefix;
        }
        return $prefix;
    }
}